import request from '../../../../util/request.js'
import cheerio from 'cheerio'

const get_news = function (url,callback) {
  if (arguments.length !== 2)  throw 'params Length error'
  let parseContent = []
  if (!url) return callback({code: 200, err: 'no url'})
  const baseUrl = 'https://s.weibo.com'
  const options = {
    url,
    method: 'get',
    headers: {
      'Content-Type': 'text/html; charset=UTF-8',
      'User-Agent':' Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36',
      "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
      "Cookie": "SUBP=0033WrSXqPxfM72-Ws9jqgMF55529P9D9WFkQmBWMEWBIos-XkorKMKL; _s_tentry=passport.weibo.com; Apache=4937972962585.711.1646359638832; SINAGLOBAL=4937972962585.711.1646359638832; ULV=1646359638990:1:1:1:4937972962585.711.1646359638832:; SUB=_2AkMVfQpzf8NxqwJRmP4QyGzkZIR1ww_EieKjIfuoJRMxHRl-yj92qmU5tRB6Pv0knGVrH45iIAzM0WfGjokXQhF8nZLO",
      "referer": url
    }
  }
  request(options).then((result) => {
      const $ = cheerio.load(result, {decodeEntities: false})
      const parseBody = $('#pl_top_realtimehot tbody tr td.td-02')
      const validItems = Array.prototype.filter.call(parseBody,(item) => {
        return !$(item).find('a').attr('action-type')
      })
      validItems.forEach((e, index) => {
        const title = $(e).find('a').text()
        const url = $(e).find('a').attr('href')
        const hot = $(e).find('span').text()
        parseContent.push({
          title,
          url: baseUrl + (url),
          hot: ~~(hot.replace(/\D/g,''))
        })
      })
     callback({code: 0, data: parseContent})
  }).catch((err) => {
    callback({code:500, err})
    return err
  });
}


export default get_news